package com.lc.hongtai.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lc.hongtai.R;
import com.lc.hongtai.adapter.RecyclerAdapter;
import com.lc.hongtai.conn.JsonAccessToken;
import com.lc.hongtai.conn.JsonInvest;
import com.lc.hongtai.conn.JsonInvestfilter;
import com.lc.hongtai.toast.LovelyToast;
import com.lc.hongtai.view.ScrollSpeedLinearLayoutManger;
import com.lc.hongtai.view.SimpleDividerItemDecoration;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.http.AsyCallBack;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.indicator.PtrIndicator;

/**
 * Created by Administrator on 2017/4/24.
 */

public class InvestListActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.rv_01)
    RecyclerView rv01;


    @Bind(R.id.store_house_ptr_frame)
    PtrFrameLayout store_house_ptr_frame;
    private PtrClassicDefaultHeader header;
    private int isInvest = 1;//MyInvestlistAdapter.INVESTMODE
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<String> list0 = new ArrayList<>();
    private List<String> list1 = new ArrayList<>();
    private List<String> list2 = new ArrayList<>();
    private List<String> list3 = new ArrayList<>();
    public List<JsonInvestfilter.Info.ListContent> borrowTypeList;
    //    public List<JsonInvestfilter.Info.ListContent> borrowInterestRateList;
    public List<JsonInvestfilter.Info.ListContent> borrowDurationList;
    public List<JsonInvestfilter.Info.ListContent> borrowStatusList;
    private List<JsonInvest.Info.ListContent> list = new ArrayList<>();

    public int nowPage = 1;
    public int totalPages = 1;
    public int pageSize = 0;
    public int totalRows = 0;
    public boolean canLoadMore = true;
    private String show_type = "normal";


    private PopupWindow popLeft;
    private View layoutLeft;
    private ListView menulistLeft;
    private String select_id;

    private String shouyi_id;

    private String qixian_id;

    private String toubiao_id;


    ScrollSpeedLinearLayoutManger scrollSpeedLinearLayoutManger;

    @BoundView(R.id.transaction_zhaiquan)
    private TextView transaction_zhaiquan;
    private RecyclerAdapter adapter;

    @BoundView(R.id.iv_back)
    private ImageView iv_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_investlist);

        ButterKnife.bind(this);


        initView();

        initRefreshListener();

    }

    private void initView() {

        rv01.setHasFixedSize(true);


        scrollSpeedLinearLayoutManger = new ScrollSpeedLinearLayoutManger(InvestListActivity.this);
        //rv01.setLayoutManager(scrollSpeedLinearLayoutManger);
        //   rv01.setLayoutManager(mLayoutManager);
        //  mAdapter = new MyInvestlistAdapter_New(InvestListActivity.this, list, isInvest);
        //    mAdapter=RecyclerAdapter_New(InvestListActivity.this);
        mAdapter = new RecyclerAdapter(InvestListActivity.this, list);
        mLayoutManager = new LinearLayoutManager(this);
        rv01.setLayoutManager(mLayoutManager);
        // adapter = new RecyclerAdapter(InvestListActivity.this, list);


        //   rv01.setAdapter(adapter);

        Drawable drawable = ContextCompat.getDrawable(InvestListActivity.this, R.drawable.line_divider);
        rv01.addItemDecoration(new SimpleDividerItemDecoration(InvestListActivity.this, drawable, 30));
        rv01.setAdapter(mAdapter);
        header = new PtrClassicDefaultHeader(InvestListActivity.this);
        store_house_ptr_frame.setHeaderView(header);
        transaction_zhaiquan.setOnClickListener(this);
        //返回按钮
        iv_back.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (list0.isEmpty()) {
            getTypeAccessToken();
        } else {
            // list.clear();
            nowPage = 1;
            initData(false, nowPage);
        }
    }

    private void initRefreshListener() {
        rv01.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
                if (dy > 0 && lastVisibleItemPosition + 1 == mAdapter.getItemCount() && canLoadMore) {
               /*     rv01.setOnTouchListener(
                            new View.OnTouchListener() {
                                @Override
                                public boolean onTouch(View v, MotionEvent event) {
                                    if (true) {
                                        return true;
                                    } else {
                                        return false;
                                    }
                                }
                            }
                    );
*/
                    canLoadMore = false;
                    if (nowPage < totalPages) {
                        initData(true, nowPage + 1);
                    } else {


                        LovelyToast.makeText(InvestListActivity.this, "没有更多了~", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    }
                }
            }
        });

        store_house_ptr_frame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                int firstVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findFirstCompletelyVisibleItemPosition();
                return (firstVisibleItemPosition == 0 || list.size() == 0) && list0.size() != 0;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //
                //     list.clear();
                nowPage = 1;
                initData(false, nowPage);
            }
        });
        store_house_ptr_frame.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIReset(PtrFrameLayout frame) {
                header.onUIReset(frame);
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {
                header.onUIRefreshPrepare(frame);
            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                header.onUIRefreshBegin(frame);
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {
                header.onUIRefreshComplete(frame);
            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                header.onUIPositionChange(frame, isUnderTouch, status, ptrIndicator);
            }
        });
    }


    @Override
    public void onClick(View view) {
        super.onClick(view);

        switch (view.getId()) {
            case R.id.transaction_zhaiquan:
                startActivity(new Intent(InvestListActivity.this, TransitionActivity.class));

                break;
            case R.id.iv_back:
                finish();
                break;

        }

    }


    private void initData(boolean b, final int page) {
        getInvestDataAccessToken(b, page);
    }


    private void getInvestDataAccessToken(final boolean b, final int page) {
        new JsonAccessToken("index/invest", new AsyCallBack<JsonAccessToken.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {

                if (info != null) {
                    if (!TextUtils.isEmpty(info.access_token)) {
                        initInvestData(info.access_token, b, page);
                    } else {
                        //UtilToast.show(NewsActivity.this, "安全验证失败！");
                        LovelyToast.makeText(InvestListActivity.this, "安全验证失败~", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                        canLoadMore = true;
                        if (!b) {
                            store_house_ptr_frame.refreshComplete();
                        }
                    }

                }

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                canLoadMore = true;
                LovelyToast.makeText(InvestListActivity.this, "安全验证失败", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }
        }).execute(InvestListActivity.this, false);

    }


    private void initInvestData(String access_token, final boolean isShow, final int page) {
        Log.d(shouyi_id, "7777777777777777777777777777777777");
        // new JsonInvest(access_token, show_type, String.valueOf(page), borrowTypeList.get(sp01.getSelectedItemPosition()).id, borrowInterestRateList.get(sp02.getSelectedItemPosition()).id, borrowDurationList.get(sp03.getSelectedItemPosition()).id, borrowStatusList.get(sp04.getSelectedItemPosition()).id, new AsyCallBack<JsonInvest.Info>() {
        new JsonInvest(access_token, show_type, String.valueOf(page), select_id, qixian_id, toubiao_id, new AsyCallBack<JsonInvest.Info>() {

            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
                showLoading();
            }

            @Override
            public void onSuccess(String toast, int type, JsonInvest.Info info) throws Exception {
                if (info != null) {
                //    list.clear();
                    list.addAll(info.list);
                    nowPage = info.page.nowPage;
                    totalPages = info.page.totalPages;
                    pageSize = info.page.pageSize;
                    totalRows = info.page.totalRows;
//                    if (list.isEmpty()) {
//                        UtilToast.show(getActivity(), "无相关记录！");
//                    }
                }
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                LovelyToast.makeText(InvestListActivity.this, "安全验证失败", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
                dismissLoading();
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                dismissLoading();
                if (!isShow) {
                    store_house_ptr_frame.refreshComplete();
                }
                canLoadMore = true;
                mAdapter.notifyDataSetChanged();
            }

        }).execute(InvestListActivity.this, isShow);
    }


    private void getTypeAccessToken() {
        new JsonAccessToken("index/invest_filter", new AsyCallBack<JsonAccessToken.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {
                if (info != null) {
                    if (!TextUtils.isEmpty(info.access_token)) {
                        initTypeData(info.access_token);
                    } else {

                        LovelyToast.makeText(InvestListActivity.this, "安全验证失败！", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    }
                }
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                LovelyToast.makeText(InvestListActivity.this, "安全验证失败", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }
        }).execute(InvestListActivity.this, false);
    }

    private void initTypeData(String access_token) {
        new JsonInvestfilter(access_token, new AsyCallBack<JsonInvestfilter.Info>() {

            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
                //  showLoading();


            }

            @Override
            public void onSuccess(String toast, int type, JsonInvestfilter.Info info) throws Exception {
                if (info != null) {
                    borrowTypeList = info.borrow_type;
                    //borrowInterestRateList = info.borrowInterestRateList;
                    borrowDurationList = info.borrow_duration;
                    borrowStatusList = info.borrow_status;
                    for (int i = 0; i < borrowTypeList.size(); i++) {
                        list0.add(borrowTypeList.get(i).name);
                    }
                /*    for (int i = 0; i < borrowInterestRateList.size(); i++) {
                        list1.add(borrowInterestRateList.get(i).name);
                    }*/
                    for (int i = 0; i < borrowDurationList.size(); i++) {
                        list2.add(borrowDurationList.get(i).name);
                    }
                    for (int i = 0; i < borrowStatusList.size(); i++) {
                        list3.add(borrowStatusList.get(i).name);
                    }

                    select_id = borrowTypeList.get(0).id;
                    toubiao_id = borrowStatusList.get(0).id;

                    nowPage = 1;
                    initData(false, nowPage);
                } else {

                 /*   LovelyToast.makeText(getActivity(), JsonInvestfilter.TOAST, 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);*/
                    LovelyToast.makeText(InvestListActivity.this, "安全验证失败", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                }
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                //   dismissLoading();
                mAdapter.notifyDataSetChanged();
            }

        }).execute(InvestListActivity.this, false);

    }
}
